package com.easonji.attendance.service.impl;

import com.easonji.admin.manager.UserManager;
import com.easonji.attendance.mapper.LeaveStateMapper;
import com.easonji.attendance.model.Leave;
import com.easonji.attendance.mapper.LeaveMapper;
import com.easonji.attendance.model.LeaveState;
import com.easonji.attendance.model.OvertimeState;
import com.easonji.attendance.query.LeaveVerifyQuery;
import com.easonji.attendance.service.ILeaveService;
import com.easonji.attendance.service.ILeaveStateService;
import com.easonji.common.base.service.AbstractBaseService;
import com.easonji.common.util.JsonUtils;
import com.easonji.common.page.PageInfo;
import com.easonji.common.util.StringUtils;
import com.easonji.common.base.query.BaseQuery;
import com.easonji.common.factory.PageFactory;

import com.easonji.core.exception.BizException;
import com.easonji.core.shiro.ShiroUser;
import com.easonji.core.shiro.util.ShiroUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 请假 服务实现类
 * </p>
 *
 * @author easonji
 * @since 2018-10-03
 */
@Service
public class LeaveServiceImpl extends AbstractBaseService<Leave> implements ILeaveService {

    @Resource
    private LeaveMapper leaveMapper;

    @Resource
    private LeaveStateMapper leaveStateMapper;

    @Resource
    private UserManager userManager;

    @Resource
    private ILeaveStateService leaveStateService;

    @Override
    protected JSONObject warp2Json(Leave leave) {
       JSONObject result = JsonUtils.parseObject(leave);

        result.put("leUserName",userManager.getUserNameById(leave.getLeUser()));
        result.put("leStateName",getStateName(leave.getLeState()));
        result.put("leTypeName",getTypeName(leave.getLeType()));
        result.put("leStrDate",leave.getLeStrDate().substring(0,19));
        result.put("leEndDate",leave.getLeEndDate().substring(0,19));
       return result;
    }


    @Override
    public Object queryList(BaseQuery baseQuery){

        // 分页信息
        Page<Leave> page = new PageFactory<Leave>().defaultPage();
        // 查询条件
        Wrapper<Leave> wrapper = new EntityWrapper<>();

        String beginTime = baseQuery.getBeginTime();
        if (StringUtils.isNotEmpty(beginTime)) {
            wrapper.ge("le_str_date", beginTime);
        }
        String endTime = baseQuery.getEndTime();
        if (StringUtils.isNotEmpty(endTime)) {
            wrapper.le("le_str_date", endTime);
        }

        ShiroUser shiroUser = ShiroUtils.getUser();
        //查询本人创建的和上级为本人创建的单子
        wrapper.and("(le_user ={0} or le_create_user={0})",shiroUser.getUserId());

        wrapper.orderBy("le_id",false);

        List<Leave> leaves = leaveMapper.selectPage(page, wrapper);

        return new PageInfo(warp(leaves), page.getTotal());
    }

    @Override
    public Object queryRowById(Integer leId) {
        Leave leave = leaveMapper.selectById(leId);
        return warp(leave);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = BizException.class)
    public Integer save(Leave leave,List<Map<String,Integer>> Auditors) {

        Integer insertint = leaveMapper.insert(leave);
        if(insertint==0){
            return 0;
        }

        LeaveState leaveState = new LeaveState();
        leaveState.setLesAuditor(leave.getLeCreateUser());
        leaveState.setLesDatetime(new Date());
        leaveState.setLesLeave(leave.getLeId());
        leaveState.setLesState(1);

        insertint = leaveStateMapper.insert(leaveState);
        if(insertint==0){
            return 0;
        }

        for(Map<String,Integer> map : Auditors){
            leaveState = new LeaveState();
            leaveState.setLesAuditor(map.get("user"));
            leaveState.setLesPost(map.get("post"));
            leaveState.setLesLeave(leave.getLeId());
            leaveState.setLesState(0);
            insertint = leaveStateMapper.insert(leaveState);
            if(insertint==0){
                return 0;
            }
        }

        return insertint;
    }

    @Override
    public Integer update(Leave leaveForm) {
        Leave leave = new Leave();
        BeanUtils.copyProperties(leaveForm,leave);
        return leaveMapper.updateById(leave);
    }

    @Override
    public Integer delete(Integer leId) {
        Wrapper<Leave> wrapper = new EntityWrapper<>();
        wrapper.eq("le_id", leId);
        return leaveMapper.delete(wrapper);
    }

    @Override
    public Object queryVerifyList(LeaveVerifyQuery leaveVerifyQuery){

        ShiroUser shiroUser = ShiroUtils.getUser();



        // 分页信息
        Page<Leave> page = new PageFactory<Leave>().defaultPage();
        // 查询条件
        Wrapper<Leave> wrapper = new EntityWrapper<>();

        String beginTime = leaveVerifyQuery.getBeginTime();
        if (StringUtils.isNotEmpty(beginTime)) {
            wrapper.ge("le_str_date", beginTime);
        }
        String endTime = leaveVerifyQuery.getEndTime();
        if (StringUtils.isNotEmpty(endTime)) {
            wrapper.le("le_str_date", endTime);
        }

        //如果是2则查 历吏审核的
        if(leaveVerifyQuery.getState()!=null && leaveVerifyQuery.getState()==2){
            List<Integer> oids = leaveStateService.queryLeaveIdByauditor(shiroUser.getUserId()); //查询历吏审核的 ID
            if(oids.size()==0){
                wrapper.eq("le_id",0);
            }else{
                wrapper.in("le_id",oids);
            }

        }else{
            wrapper.eq("le_next_auditor",shiroUser.getUserId());
        }



        wrapper.orderBy("le_id",false);

        List<Leave> leaves = leaveMapper.selectPage(page, wrapper);



        return new PageInfo(warp(leaves), page.getTotal());
    }

    private String getStateName(Integer state){
        String stateName = null;

        if(state == null){
            return "";
        }
        switch(state){
            case 0:
                stateName = "申请成功，等待审核";
                break;
            case 1:
                stateName = "线长审核通过，等待主管审核";
                break;
            case 2:
                stateName = "审核通过";
                break;
            case -1:
                stateName = "线长不通过";
                break;
            case -2:
                stateName = "主管不通过";
                break;
            default :
                stateName = "";
        }

        return stateName;
    }

    /**
     * 请假类型
     * @param type
     * @return
     */
    private String getTypeName(Integer type){
        String typeName = null;

        if(type == null){
            return "";
        }
        switch(type){
            case 1:
                typeName = "事假";
                break;
            case 2:
                typeName = "病假";
                break;
            case 3:
                typeName = "年假";
                break;
            case 4:
                typeName = "婚假";
                break;
            case 5:
                typeName = "产假";
                break;
            case 6:
                typeName = "陪产假";
                break;
            case 7:
                typeName = "路途假";
                break;
            case 8:
                typeName = "其它";
                break;
            default :
                typeName = "";
        }

        return typeName;
    }

}
